package org.example.Day11.TCP;
import java.io.*;
import java.net.Socket;

public class ServerReaderThread1 extends Thread {
    private Socket socket;

    public ServerReaderThread1(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            InputStream is = socket.getInputStream();
            DataInputStream dis = new DataInputStream(is);
            while (true) {
                try {
                    String msg = dis.readUTF();
                    System.out.println(msg);
                    sendMsgToAll(msg);
                } catch (Exception e) {
                    System.out.println("有⼈下线了：" + socket.getRemoteSocketAddress());
                    Server1.onLineSockets.remove(socket);
                    dis.close();
                    socket.close();
                    break;
                }
            }
        }catch(Exception e){
            e.printStackTrace();
        }

    }
    private void sendMsgToAll(String msg) throws IOException {
                // 发送给全部在线的socket管道接收。
                for (Socket onLineSocket : Server1.onLineSockets) {
                        OutputStream os = onLineSocket.getOutputStream();
                        DataOutputStream dos = new DataOutputStream(os);
                        dos.writeUTF(msg);
                        dos.flush();
            }
    }
}



